package cn.chengpengper.rpc.test.consumer.codec.handler;

import cn.chengpengper.rpc.protocol.RpcProtocol;
import cn.chengpengper.rpc.protocol.enums.RpcType;
import cn.chengpengper.rpc.protocol.header.RpcHeaderFactory;
import cn.chengpengper.rpc.protocol.request.RpcRequest;
import cn.chengpengper.rpc.protocol.response.RpcResponse;
import cn.hutool.json.JSONUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author chengpeng.hu
 */
@Slf4j
public class RpcTestConsumerHandler extends SimpleChannelInboundHandler<RpcProtocol<RpcResponse>> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcProtocol<RpcResponse> resp) throws Exception {
        log.info("服务消费者接收到的数据====>{}", JSONUtil.toJsonStr(resp));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("发送数据开始");
        // 模拟发送数据
        RpcProtocol<RpcRequest> protocol = new RpcProtocol<>();
        protocol.setHeader(RpcHeaderFactory.getRequestHeader("jdk", RpcType.REQUEST));
        RpcRequest request = new RpcRequest();
        request.setClassName("cn.chengpengper.rpc.test.api.RealMethodDemoService");
        request.setGroup("catwing");
        request.setMethodName("hello");
        request.setParameters(new Object[]{"catwing-helloword"});
        request.setParameterTypes(new Class[]{String.class});
        request.setVersion("1.0.0");
        request.setAsync(false);
        request.setOneway(false);
        protocol.setBody(request);
        log.info("服务消费者发送的数据====>{}", JSONUtil.toJsonPrettyStr(protocol));
        ctx.writeAndFlush(protocol);
        log.info("发送数据结束");
    }
}
